<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言在React-Router中，WEB端的Router提供了两种不同的模式：hash模式和history模式。hash模式即HashRouter是基于hash实现的一种路由方式，URL变化时主要是hash值进行变化。hash模式的好处是一定不会向服务端发送请求，但URL里一定会有一个#号。 BrowserRouter则是基于H5 historyAPI的一种路由方式。history的URL切换基于">
<meta property="og:type" content="article">
<meta property="og:title" content="react修炼（三）-router">
<meta property="og:url" content="http://example.com/2021/11/12/react/react%E4%BF%AE%E7%82%BC(%E4%B8%89)-router/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言在React-Router中，WEB端的Router提供了两种不同的模式：hash模式和history模式。hash模式即HashRouter是基于hash实现的一种路由方式，URL变化时主要是hash值进行变化。hash模式的好处是一定不会向服务端发送请求，但URL里一定会有一个#号。 BrowserRouter则是基于H5 historyAPI的一种路由方式。history的URL切换基于">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-12T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-12T07:21:35.926Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="react初学">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/11/12/react/react%E4%BF%AE%E7%82%BC(%E4%B8%89)-router/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>react修炼（三）-router | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/12/react/react%E4%BF%AE%E7%82%BC(%E4%B8%89)-router/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react修炼（三）-router
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              
    
              <time title="创建时间：2021-11-12 12:18:39 / 修改时间：15:21:35" itemprop="dateCreated datePublished" datetime="2021-11-12T12:18:39+08:00">2021-11-12</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>在React-Router中，WEB端的Router提供了两种不同的模式：hash模式和history模式。hash模式即HashRouter是基于hash实现的一种路由方式，URL变化时主要是hash值进行变化。hash模式的好处是一定不会向服务端发送请求，但URL里一定会有一个#号。</p>
<p>BrowserRouter则是基于H5 historyAPI的一种路由方式。history的URL切换基于history提供的pushState方法。在项目上，使用时需要在项目的最外层配置好路由，并说明使用的是哪种路由。</p>
<p>上面的两种模式只是提供了不同的路由选择，本质上真正的路由还是使用Route组件，当浏览器中的URL与Router组件中的path匹配时，会呈现对应的UI。</p>
<p>path匹配默认情况下是一种模糊匹配，若当前URL是以该path开始的就会被匹配。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;Route path=<span class="string">"/"</span> component=&#123;IndexView&#125; /&gt;</span><br><span class="line">&lt;Route path=<span class="string">"/about"</span> component=&#123;AboutView&#125; /&gt;</span><br><span class="line">&lt;Route path=<span class="string">"/about/details"</span> component=&#123;AboutDetailsView&#125; /&gt;</span><br></pre></td></tr></table></figure>

<p>当浏览器URL为/about/details时，会发现这三个路由都会被渲染。如果希望URL和path必须一致时才匹配，就可以使用精确匹配，只要把Route的exact属性设置为true。</p>
<p>1、多路径匹配：path中传递一个数组；数组中存放多个路径，当其中一个路径与URL匹配时，则认定该路由匹配当前URL。</p>
<p>2、path参数，及通过path进行一些参数的传递。例如：路由信息，或者路由参数params的传递。</p>
<p>路由渲染：通过路由渲染视图的常用写法有以下两种：component和render。</p>
<p>1、component：使用Route的component属性渲染视图时，，要给component传入一个组件，该组件是路由匹配时要渲染的视图。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123;Fragment&#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;Route&#125; <span class="keyword">from</span> <span class="string">"react-router-dom"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">About</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>关于我们视图内容<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">Fragment</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">Route</span> <span class="attr">path</span>=<span class="string">"/about"</span> <span class="attr">component</span>=<span class="string">&#123;About&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;/<span class="name">Fragment</span>&gt;</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2、render，使用Route的render属性渲染视图时，要给render属性传递一个函数，函数必须有返回值，可以是视图组件或者JSX。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123;Fragment&#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;Route&#125; <span class="keyword">from</span> <span class="string">"react-router-dom"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">About</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>关于我们视图内容<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">Fragment</span>&gt;</span></span></span><br><span class="line">        &lt;Route path="/about" render=&#123;() =&gt; (&lt;div&gt;用户中心视图&lt;div&gt;)&#125; /&gt;</span><br><span class="line">            &lt;/Fragment&gt;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="路由信息"><a href="#路由信息" class="headerlink" title="路由信息"></a>路由信息</h1><p>被路由直接调用的组件一般称之为路由组件，Route在调用路由组件时会给该组件传递history、location、match三个参数，从这三个参数中可以获取到当前路由的一些信息。</p>
<p>1、history是在H5 history基础上封装处理的一个新对象，该对象下常用方法和属性如下。l</p>
<p>ength：该域下历史记录的条目；location：URL的信息，具体参考location对象；</p>
<p>push(path, [state])：将新条目推入历史记录对战，这里也是跳转URL的方法。例如单击按钮时想要跳转链接，就可以使用history.push(“url”)。state要传递给新的路由组件的额外信息，会被新路由组件中loaction的state接收；</p>
<p>replace(path,[state]):替换历史记录上的当前条目。这样同样会引发URL跳转，不同的是：此时会在历史记录中替换掉之前的记录。</p>
<p>go(n)，跳转n步历史记录，正数向前n步，负数后退n步。</p>
<p>2、location对象：浏览器地址栏相关信息，常用属性如下：</p>
<p>pathname：URL的路径，格式为字符串；search：URL中的search片段，格式为字符串；hash：URL中的hash片段，格式为字符串；state：路由跳转时传递的额外信息，如push(path, state)推送过来的state信息，格式为对象。</p>
<p>3、match对象：路由的匹配信息，常用属性如下：</p>
<p>params：接收path参数(:page)传递过来的相关信息，格式为对象；isExact：指是否精确匹配；path：Route中定义的path路径。</p>
<p>在获取路由信息时，只有通过Route component调用的组件才会被传递路由信息。而render调用时Route会把路由信息传递给函数，若想把参数传递给组件则需要开发者手动传递。</p>
<h2 id="非路由组件"><a href="#非路由组件" class="headerlink" title="非路由组件"></a>非路由组件</h2><p>非路由组件有时候也要获取路由信息，在React Router方法中提供了两种方法来方便开发者获取。</p>
<h3 id="withRouter"><a href="#withRouter" class="headerlink" title="withRouter"></a>withRouter</h3><p>withRouter的作用有点类似于Redux中的connnect，把要获取路由信息的组件传入withRouter，withRouter会把路由信息传递给该组件，并会返回一个新的组件，来方便其他地方调用。具体使用示例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;withRouter&#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span>;</span><br><span class="line">fucntion backBtn(props) &#123;</span><br><span class="line">    <span class="keyword">let</span> &#123;history&#125; = props;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span> = <span class="string">&#123;()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="xml">       history.goBack(); </span></span><br><span class="line"><span class="xml">    &#125;&#125;&gt;返回上一页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line">backBtn = withRouter(backBtn);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> backBtn;</span><br></pre></td></tr></table></figure>

<h3 id="Router-Hooks"><a href="#Router-Hooks" class="headerlink" title="Router Hooks"></a>Router Hooks</h3><p>使用规则与React中的其他Hooks一样；useHistory调用该Hook会返回history对象，useLocation调用该Hook会返回location对象，useRouteMatch调用该Hook会返回match对象，useParams调用该Hook会返回match对象中的params，也就是path传递的参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;useHistory&#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span>;</span><br><span class="line">fucntion backBtn(props) &#123;</span><br><span class="line">    <span class="keyword">let</span> history = useHistory;</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span> = <span class="string">&#123;()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="xml">       history.goBack(); </span></span><br><span class="line"><span class="xml">    &#125;&#125;&gt;返回上一页<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line">backBtn = withRouter(backBtn);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> backBtn;</span><br></pre></td></tr></table></figure>

<h2 id="链接跳转"><a href="#链接跳转" class="headerlink" title="链接跳转"></a>链接跳转</h2><p>如果使用A标签跳转的化，会导致视图刷新，而只做视图跳转而不是外部链接的化，建议使用Router中专门的组件Link和NavLink。</p>
<h3 id="Link"><a href="#Link" class="headerlink" title="Link"></a>Link</h3><p>Link专门用来做跳转链接，其to属性定义的是单击后要跳转的链接地址。to的属性值有两种形式：字符串和对象。</p>
<p>1、当to属性为字符串时，链接地址的编写和正常URL没有区别；</p>
<p>2、当to的属性为对象时，则链接地址的编写需要放入对象的相关属性中：</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;Link </span><br><span class="line">    to=&#123;&#123;</span><br><span class="line">        pathname: <span class="string">"/about"</span>,</span><br><span class="line">        search: <span class="string">"?search=search值"</span>,</span><br><span class="line">        hash: <span class="string">"#hash值"</span>,</span><br><span class="line">        state: &#123;<span class="attr">info</span>: <span class="string">"要传递的其他信息"</span>&#125;</span><br><span class="line">    &#125;&#125;</span><br><span class="line">    &gt;About&lt;<span class="regexp">/Link&gt;</span></span><br></pre></td></tr></table></figure>

<p>这几个属性的作用分别为：pathname代表链接路径的字符串；search代表URL中的search值，hash代表URL中的hash值；state代表要传递给视图的其他信息。</p>
<h3 id="NavLink"><a href="#NavLink" class="headerlink" title="NavLink"></a>NavLink</h3><p>NavLink是一种特殊的Link，一般用作导航中的Link，格式与Link组件一致，且可制作导航的选中效果。在NavLink中有activeClassName、activeStyle、isActive三个属性来进行选中的设置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; Fragment &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Route, NavLink, useLocation &#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span>;</span><br><span class="line"><span class="keyword">const</span> navData = [</span><br><span class="line">  &#123;</span><br><span class="line">      pathName:<span class="string">"/"</span>,</span><br><span class="line">      style:&#123;<span class="attr">color</span>:<span class="string">"red"</span>&#125;,</span><br><span class="line">      title:<span class="string">"首页"</span>,</span><br><span class="line">      render()&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>首页视图内容<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    pathName:<span class="string">"/about"</span>,</span><br><span class="line">    style:&#123;<span class="attr">color</span>:<span class="string">"red"</span>&#125;,</span><br><span class="line">    title:<span class="string">"关于我们"</span>,</span><br><span class="line">    render()&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>关于我们视图内容<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Nav</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> &#123;pathname&#125; = useLocation();</span><br><span class="line">    <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">nav</span>&gt;</span></span></span><br><span class="line"><span class="xml">        &#123;navData.map(item=&gt;&#123;</span></span><br><span class="line">            return &lt;NavLink </span><br><span class="line">              key=&#123;item.pathName&#125;</span><br><span class="line">              to=&#123;item.pathName&#125; </span><br><span class="line">              activeStyle=&#123;item.style&#125;</span><br><span class="line">              isActive=&#123;()=&gt;&#123;</span><br><span class="line">                  return pathname === item.pathName;</span><br><span class="line">              &#125;&#125;</span><br><span class="line"><span class="xml">            &gt;&#123;item.title&#125;<span class="tag">&lt;/<span class="name">NavLink</span>&gt;</span></span></span><br><span class="line"><span class="xml">        &#125;)&#125;</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">nav</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">Fragment</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">Nav</span> /&gt;</span></span></span><br><span class="line"><span class="xml">        &#123;navData.map(item=&gt;&#123;</span></span><br><span class="line"><span class="xml">            return <span class="tag">&lt;<span class="name">Route</span> <span class="attr">key</span>=<span class="string">&#123;item.pathName&#125;</span> <span class="attr">path</span>=<span class="string">&#123;item.pathName&#125;</span> <span class="attr">exact</span> <span class="attr">render</span>=<span class="string">&#123;item.render&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="xml">        &#125;)&#125;</span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">Fragment</span>&gt;</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>

<h3 id="404"><a href="#404" class="headerlink" title="404"></a>404</h3><p>404视图：当用户访问一些不存在的URL时返回404视图。一般使用Switch组件包裹Route，当一项匹配成功后，就不再匹配后续。这样可以把要匹配的内容写在Switch组件中，最后一项写404视图，当其他都不匹配成功时，就返回404视图。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; Fragment &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Route, Switch &#125; <span class="keyword">from</span> <span class="string">'react-router-dom'</span>;</span><br><span class="line"><span class="keyword">import</span> Nav <span class="keyword">from</span> <span class="string">'./component/nav'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;routes&#125; <span class="keyword">from</span> <span class="string">"./route/router"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">Fragment</span>&gt;</span></span></span><br><span class="line"><span class="xml">      <span class="tag">&lt;<span class="name">Nav</span> /&gt;</span></span></span><br><span class="line">      &lt;Switch&gt;</span><br><span class="line">          &#123;routes.map(item=&gt;&#123;</span><br><span class="line">              return &lt;Route </span><br><span class="line">                  key=&#123;item.path&#125;</span><br><span class="line">                  path=&#123;item.path&#125;</span><br><span class="line">                  exact=&#123;item.exact&#125;</span><br><span class="line">                  render=&#123;item.render&#125;</span><br><span class="line">              /&gt;</span><br><span class="line">          &#125;)&#125;</span><br><span class="line"><span class="xml">      <span class="tag">&lt;/<span class="name">Switch</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">Fragment</span>&gt;</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*route.js*/</span></span><br><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">"react"</span>;</span><br><span class="line"><span class="keyword">import</span> IndexView <span class="keyword">from</span> <span class="string">"../view/index"</span>;</span><br><span class="line"><span class="keyword">import</span> AboutView <span class="keyword">from</span> <span class="string">"../view/about"</span>;</span><br><span class="line"><span class="keyword">import</span> ListView <span class="keyword">from</span> <span class="string">"../view/list"</span>;</span><br><span class="line"><span class="keyword">import</span> UndefinedView <span class="keyword">from</span> <span class="string">"../view/404"</span>;</span><br><span class="line"><span class="keyword">let</span> routes=[&#123;</span><br><span class="line">    path:<span class="string">"/"</span>,</span><br><span class="line">    exact: <span class="literal">true</span>,</span><br><span class="line">    render(props)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">IndexView</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">    &#125;   </span><br><span class="line">&#125;,&#123;</span><br><span class="line">    path:<span class="string">"/about"</span>,</span><br><span class="line">    exact: <span class="literal">true</span>,</span><br><span class="line">    render(props)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">AboutView</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">    &#125;   </span><br><span class="line">&#125;,&#123;</span><br><span class="line">    path:[<span class="string">"/list"</span>,<span class="string">"/list/:page"</span>],</span><br><span class="line">    exact: <span class="literal">true</span>,</span><br><span class="line">    render(props)&#123;</span><br><span class="line">        <span class="keyword">let</span> &#123;page=<span class="number">1</span>&#125; = props.match.params;</span><br><span class="line">        <span class="comment">// 解构页码，如果没有传递页面设置默认值为 1。</span></span><br><span class="line">        <span class="keyword">if</span>(page &gt;= <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="comment">// 判断页面是否为 &gt; 1 的数字，如 /list/a 等不是数字的情况下，则显示 404 视图</span></span><br><span class="line">            <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">ListView</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">UndefinedView</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">    &#125;   </span><br><span class="line">&#125;,&#123;</span><br><span class="line">    path:<span class="string">""</span>,</span><br><span class="line">    exact: <span class="literal">false</span>,</span><br><span class="line">    render(props)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">UndefinedView</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line">    &#125;   </span><br><span class="line">&#125;];</span><br><span class="line"><span class="keyword">let</span> navs = [</span><br><span class="line">    &#123;</span><br><span class="line">        to:<span class="string">"/"</span>,</span><br><span class="line">        exact: <span class="literal">true</span>,</span><br><span class="line">        title:<span class="string">"首页"</span>  </span><br><span class="line">    &#125;,&#123;</span><br><span class="line">        to:<span class="string">"/about"</span>,</span><br><span class="line">        exact: <span class="literal">true</span>,</span><br><span class="line">        title: <span class="string">"关于"</span>   </span><br><span class="line">    &#125;,&#123;</span><br><span class="line">        to:<span class="string">"/list"</span>,</span><br><span class="line">        title: <span class="string">"课程列表"</span>,</span><br><span class="line">        isActive(url)&#123;</span><br><span class="line">            <span class="keyword">let</span> urlData = url.split(<span class="string">"/"</span>); </span><br><span class="line">            <span class="keyword">if</span>(url === <span class="string">"/list"</span></span><br><span class="line">            ||(urlData.length===<span class="number">3</span>&amp;&amp;urlData[<span class="number">1</span>] === <span class="string">"list"</span>&amp;&amp;urlData[<span class="number">2</span>]&gt;<span class="number">0</span>) )&#123;</span><br><span class="line">                <span class="comment">// 判断 URL 为 "/list" 或 "/list/大于1的数字" 时，选中当前项，否则不选中 </span></span><br><span class="line">                <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;   </span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;   </span><br><span class="line">    &#125;</span><br><span class="line">];</span><br><span class="line"><span class="keyword">export</span> &#123;routes,navs&#125;;</span><br></pre></td></tr></table></figure>


    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/11/12/react/react%E4%BF%AE%E7%82%BC(%E4%B8%89)-router/" title="react修炼（三）-router">http://example.com/2021/11/12/react/react修炼(三)-router/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react%E5%88%9D%E5%AD%A6/" rel="tag"># react初学</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/11/11/react/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/" rel="prev" title="react修炼（二）-Redux">
      <i class="fa fa-chevron-left"></i> react修炼（二）-Redux
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/11/14/react/react%E4%BF%AE%E7%82%BC(%E4%BA%94)-React%E6%BA%90%E7%A0%81/" rel="next" title="react修炼（五）-React源码">
      react修炼（五）-React源码 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由信息"><span class="nav-number">2.</span> <span class="nav-text">路由信息</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#非路由组件"><span class="nav-number">2.1.</span> <span class="nav-text">非路由组件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#withRouter"><span class="nav-number">2.1.1.</span> <span class="nav-text">withRouter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Router-Hooks"><span class="nav-number">2.1.2.</span> <span class="nav-text">Router Hooks</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#链接跳转"><span class="nav-number">2.2.</span> <span class="nav-text">链接跳转</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Link"><span class="nav-number">2.2.1.</span> <span class="nav-text">Link</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#NavLink"><span class="nav-number">2.2.2.</span> <span class="nav-text">NavLink</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#404"><span class="nav-number">2.2.3.</span> <span class="nav-text">404</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

